package com.ruoyi.service.impl;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.service.ICategoryService;
import com.ruoyi.service.ICategoryService;
import com.ruoyi.web.domain.Category;
import com.ruoyi.web.domain.CategoryRegionRelation;
import com.ruoyi.web.mapper.CategoryMapper;
import com.ruoyi.web.mapper.CategoryRegionRelationMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class CategoryServiceImpl implements ICategoryService {
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private CategoryRegionRelationMapper categoryRegionRelationMapper;

    @Override
    public List<Category> selectCategoryList(Category category) {
        return categoryMapper.selectCategoryList(category);
    }

    @Override
    public Integer updateCategory(Category category) {
        Category exist = categoryMapper.selectCategoryById(category.getId());
        if(Objects.isNull(exist)){
            throw new RuntimeException("品类不存在 无法更新");
        }
        exist.setCategoryName(category.getCategoryName());
         categoryMapper.updateCategory(exist);
        return 1;
    }

    @Override
    public Category selectCategoryById(Integer categoryId) {
        return categoryMapper.selectCategoryById(categoryId);
    }

    @Override
    public Category selectCategoryByName(String categoryName) {
        return categoryMapper.selectCategoryByName(categoryName);
    }

    @Override
    @Transactional
    public Integer saveCategory(Category role) {
        if(StringUtils.isEmpty(role.getCategoryName())){
            throw new RuntimeException("品类名称不能为空");
        }
        Integer categoryId;
        Category exist = categoryMapper.selectCategoryByName(role.getCategoryName());
        if(Objects.isNull(exist)){
            // 如果该品类不存在
            // 1. 保存该商品并返回主键id
            categoryMapper.saveCategory(role);
            categoryId = role.getId();
        }else{
            categoryId = exist.getId();
        }
        // 2. 保存该品类与区域regionId的关系
        CategoryRegionRelation regionRelation = new CategoryRegionRelation();
        regionRelation.setCategoryId(categoryId);
        regionRelation.setRegionId(role.getRegionId());
        categoryRegionRelationMapper.saveRelation(regionRelation);
        return 1;
    }

    @Override
    public Integer deleteRelation(Integer vcrId) {
        return categoryRegionRelationMapper.deleteRelation(vcrId);
    }
}
